package com.example.photography.fragment.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.TextView;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.photography.Activity.My_Activity;
import com.example.photography.Activity.Product_Content;
import com.example.photography.Activity.Search_Activity;
import com.example.photography.R;
import com.example.photography.adapter.home_recommed.Item_productAdapter;
import com.example.photography.bean.Home_RecommendBean;
import com.example.photography.common.BaseFragment;
import com.example.photography.util.UIUtils;
import com.example.photography.util.Util;
import com.example.photography.view.MyListView;
import com.loopj.android.http.RequestParams;
import com.scwang.smart.refresh.footer.BallPulseFooter;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.SpinnerStyle;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class Home_focus extends BaseFragment {

    @BindView(R.id.lv_product)
    MyListView lvProduct;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.sw_refresh)
    SmartRefreshLayout swRefresh;
    //本次查询所有的数据
    private List<Home_RecommendBean.ProductListBean> productListBeans = new ArrayList<>();
    //本次需要加载的数据
    private List<Home_RecommendBean.ProductListBean> products_true = new ArrayList<>();
    private Item_productAdapter itemProductAdapter;
    private int mCurrPage = 0;//记录当前页
    private  int mSizePage = 5;//每页数据数量
    private boolean hasMore = true;//判断是否有更多数据需要加载
    @Override
    protected RequestParams getParams() {
        return null;
    }

    @Override
    protected String getUrl() {
        return null;
    }

    @Override
    protected void initData(String content) {
        sendhttp();
        initView();
        initListen();

    }

    private void sendhttp() {//模拟数据
        JSONObject jsonObject = JSON.parseObject(Util.getJson(getActivity(), "home_focus.json"));
        int status = jsonObject.getInteger("code");
        if (status == 202) {
            String data = jsonObject.getString("data");
            jsonObject = JSON.parseObject(data);
            String products = jsonObject.getString("product_list");
            //封装转json数据
            productListBeans = JSONObject.parseArray(products, Home_RecommendBean.ProductListBean.class);

        } else {
            // TODO: 2021/5/2 加没数据的判断
        }
    }

    private void initListen() {
        tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), Search_Activity.class);
                startActivity(intent);
            }
        });
        /**
         * 下拉刷新
         */
        swRefresh.setRefreshHeader(new ClassicsHeader(UIUtils.getContext()));
        swRefresh.setRefreshFooter(new ClassicsFooter(UIUtils.getContext()));
        //设置 Footer 为 球脉冲 样式
        swRefresh.setRefreshFooter(new BallPulseFooter(UIUtils.getContext()).setSpinnerStyle(SpinnerStyle.Scale));
        swRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                UIUtils.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //todo 有时刷新失败
                        refreshlayout.finishRefresh(false);//传入false表示刷新失败
                    }
                }, 2000);

            }
        });
        swRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {

                //非常重要的判断条件
                if(hasMore){
                    mCurrPage++;
                    getData();
                    refreshlayout.finishLoadMore(1000/*,false*/);//传入false表示加载失败
                    //更新列表
                    itemProductAdapter.notifyDataSetChanged();
                }else {
                    refreshlayout.finishLoadMore(false);//传入false表示加载失败
                }

            }
        });

//        //和下拉刷新配套使用
//        swRefresh.setOnRefreshListener(() -> {
//            //模拟网络请求需要3秒，请求完成，设置setRefreshing 为false
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    swRefresh.setRefreshing(false);
//                    //给banner重新设置数据
////                    banner.setDatas(DataBean.getTestData());
//                    //对setdatas不满意？你可以自己控制数据，可以参考setDatas()的实现修改
////                    adapter.updateData(DataBean.getTestData2());
//                }
//            }, 3000);
//        });

//        lvProduct.setOnScrollListener(new AbsListView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(AbsListView view, int scrollState) {
//
//                //非常重要的判断条件
//                if(hasMore && view.getLastVisiblePosition() == view.getCount()-1 && scrollState == SCROLL_STATE_IDLE){
//                    mCurrPage++;
//                    getData();
//                }
//            }
//
//            @Override
//            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//
//            }
//        });
    }

    private void getData() {
        int mCurrNum = mCurrPage * mSizePage;
        int offset = mCurrNum + mSizePage;
        if (offset > productListBeans.size()){
            offset = productListBeans.size();
            hasMore = false;//判断是否还有更多的数据需要加载
        }
        List<Home_RecommendBean.ProductListBean> subList = productListBeans.subList(mCurrNum, offset);
        products_true.addAll(subList);


        //更新列表
//        itemProductAdapter.notifyDataSetChanged();
    }

    private void initView() {
        itemProductAdapter = new Item_productAdapter(products_true, getActivity()) {
            @Override
            public void tofocus(String id_unique) {
                Util.showToast(mContext, "关注了该用户:" + id_unique);
            }

            @Override
            protected void toproduct_detail(String product_id) {
                Util.showToast(mContext, "点击查看该作品:" + product_id);
                Intent intent = new Intent(getActivity(), Product_Content.class);
                Bundle bundle = new Bundle();
                bundle.putString("product_id", product_id);
                intent.putExtra("data", bundle);
                startActivity(intent);
            }

            @Override
            protected void to_User_home(String id_unique) {
                Intent intent = new Intent(mContext, My_Activity.class);
                startActivity(intent);
            }
        };
        getData();
        lvProduct.setAdapter(itemProductAdapter);
    }

    @Override
    public int getLayoutId() {
        return R.layout.home_focus;
    }
}
